{% extends "base.html" %}

{% block title %}房间预订 - 风之宿{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
  <h1 class="text-3xl font-bold text-primary mb-2">房间预订</h1>
  <p class="text-gray-600 mb-8">选择理想房间，开启舒适旅程</p>

  <!-- 搜索和筛选区域 -->
  <div class="bg-white rounded-xl shadow-md p-5 mb-8">
    <h2 class="text-xl font-semibold text-gray-800 mb-4">搜索房间</h2>
    <form id="search-form" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
        <!-- 关键词搜索 -->
        <div class="lg:col-span-2">
          <label for="search-keyword" class="block text-sm font-medium text-gray-700 mb-1">关键词</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <i class="fa fa-search text-gray-400"></i>
            </div>
            <input type="text" id="search-keyword" name="keyword"
                  class="pl-10 w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                  placeholder="搜索房间名称、类型或设施">
          </div>
        </div>

        <!-- 价格范围 -->
        <div>
          <label for="price-range" class="block text-sm font-medium text-gray-700 mb-1">价格范围</label>
          <select id="price-range" name="price_range"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all">所有价格</option>
            <option value="0-200">¥200以下</option>
            <option value="200-500">¥200-¥500</option>
            <option value="500-1000">¥500-¥1000</option>
            <option value="1000+">¥1000以上</option>
          </select>
        </div>

        <!-- 房间类型 -->
        <div>
          <label for="room-type" class="block text-sm font-medium text-gray-700 mb-1">房间类型</label>
          <select id="room-type" name="room_type"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all">所有类型</option>
            <option value="standard">标准间</option>
            <option value="deluxe">豪华间</option>
            <option value="suite">套房</option>
            <option value="game">电竞房</option>
            <option value="family">家庭房</option>
          </select>
        </div>

        <!-- 容纳人数 -->
        <div>
          <label for="capacity" class="block text-sm font-medium text-gray-700 mb-1">容纳人数</label>
          <select id="capacity" name="capacity"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
            <option value="all">不限</option>
            <option value="1">1人</option>
            <option value="2">2人</option>
            <option value="3">3-4人</option>
            <option value="5+">5人以上</option>
          </select>
        </div>
      </div>

      <div class="flex flex-wrap gap-3 justify-end">
        <button type="button" id="reset-filter" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors">
          重置筛选
        </button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">
          <i class="fa fa-search mr-1"></i> 搜索房间
        </button>
      </div>
    </form>
  </div>

  <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
    <!-- 房间列表 - 占据更大空间以突出展示 -->
    <div class="lg:col-span-3">
      <div class="bg-white rounded-xl shadow-md overflow-hidden transition-shadow hover:shadow-lg">
        <div class="p-6 border-b border-gray-100 flex flex-wrap justify-between items-center">
          <div>
            <h2 class="text-2xl font-semibold text-gray-800">可选房间</h2>
            <p class="text-gray-500 mt-1">选择适合您的理想房型</p>
          </div>
          <div class="mt-3 sm:mt-0">
            <span id="room-count" class="text-sm text-gray-600">共 {{ rooms|length }} 个房间</span>
          </div>
        </div>

        <div class="divide-y divide-gray-100">
          {% for room in rooms %}
          <div class="p-6 hover:bg-gray-50 transition-colors room-item"
               data-name="{{ room.name|lower }}"
               data-price="{{ room.price }}"
               data-type="{{ room.room_type|lower }}"
               data-capacity="{{ room.capacity }}">
            <div class="flex flex-col md:flex-row gap-6">
              <!-- 房间图片 -->
              <div class="md:w-1/3 lg:w-1/4">
                <div class="rounded-lg overflow-hidden h-40 md:h-full bg-gray-100 relative group">
                  <!-- 房间状态标签 -->
                  <div class="absolute top-3 left-3 z-10">
                    {% if room.status == 'available' %}
                      <span class="px-2 py-1 bg-green-500 text-white text-xs rounded-md shadow-sm">
                        可预订
                      </span>
                    {% elif room.status == 'booked' %}
                      <span class="px-2 py-1 bg-red-500 text-white text-xs rounded-md shadow-sm">
                        已预订
                      </span>
                    {% elif room.status == 'maintenance' %}
                      <span class="px-2 py-1 bg-yellow-500 text-white text-xs rounded-md shadow-sm">
                        维护中
                      </span>
                    {% endif %}
                  </div>

                  {% if room.image_url %}
                    <img src="{{ url_for('static', filename='uploads/' + room.image_url) }}"
                         alt="{{ room.name }}"
                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
                  {% else %}
                    <img src="{{ url_for('static', filename='images/default-room.png') }}"
                         alt="默认房间图片"
                         class="w-full h-full object-cover">
                  {% endif %}
                </div>
              </div>

              <!-- 房间信息 -->
              <div class="md:w-2/3 lg:w-3/4">
                <div class="flex flex-col md:flex-row md:justify-between gap-2">
                  <div>
                    <h3 class="text-xl font-semibold text-gray-800">{{ room.name }}</h3>
                    <div class="flex items-center mt-1">
                      <span class="text-sm text-gray-500 mr-3">容纳 {{ room.capacity }} 人</span>
                      <span class="text-sm px-2 py-0.5 bg-gray-100 text-gray-600 rounded">
                        {{ room.room_type }}
                      </span>
                    </div>
                  </div>
                  <div class="text-right">
                    <span class="text-primary font-bold text-xl">¥{{ room.price }}</span>
                    <span class="text-gray-500 text-sm">/晚</span>
                  </div>
                </div>

                <p class="text-gray-600 mt-3 text-sm line-clamp-2">{{ room.description }}</p>

                <!-- 房间设施 -->
                <div class="mt-4 flex flex-wrap gap-2">
                  {% for amenity in room.amenities.split(',') %}
                    <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-full">
                      {{ amenity.strip() }}
                    </span>
                  {% endfor %}
                </div>

                <!-- 选择按钮 -->
                <div class="mt-4">
                  <button type="button"
                          class="select-room-btn px-4 py-2 border border-primary text-primary rounded-md hover:bg-primary hover:text-white transition-colors text-sm font-medium {% if room.status != 'available' %}opacity-50 cursor-not-allowed{% endif %}"
                          data-room-id="{{ room.id }}"
                          data-room-name="{{ room.name }}"
                          data-room-price="{{ room.price }}"
                          {% if room.status != 'available' %}disabled{% endif %}>
                    {% if room.status == 'available' %}选择此房间{% else %}不可预订{% endif %}
                  </button>
                </div>
              </div>
            </div>
          </div>
          {% endfor %}

          <!-- 无结果提示 -->
          <div id="no-results" class="p-12 text-center hidden">
            <i class="fa fa-search text-gray-300 text-5xl mb-4"></i>
            <h3 class="text-xl font-medium text-gray-700 mb-2">未找到符合条件的房间</h3>
            <p class="text-gray-500">请尝试调整搜索条件</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 预订表单和信息 - 固定位置便于填写 -->
    <div class="lg:col-span-2">
      <div class="sticky top-6">
        <!-- 预订表单卡片 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <h2 class="text-xl font-semibold text-gray-800 mb-5">预订信息</h2>

          <form method="POST" class="space-y-5">
            <div>
              <label for="room_id" class="block text-sm font-medium text-gray-700 mb-1">已选房间</label>
              <div class="relative">
                <input type="text" id="selected_room_display" readonly
                       class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-900"
                       placeholder="请从左侧选择房间">
                <input type="hidden" id="room_id" name="room_id" required>
              </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label for="check_in" class="block text-sm font-medium text-gray-700 mb-1">入住日期</label>
                <input type="date" id="check_in" name="check_in" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
              </div>

              <div>
                <label for="check_out" class="block text-sm font-medium text-gray-700 mb-1">退房日期</label>
                <input type="date" id="check_out" name="check_out" required
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary">
              </div>
            </div>

            <div>
              <label for="guests" class="block text-sm font-medium text-gray-700 mb-1">入住人数</label>
              <input type="number" id="guests" name="guests" min="1" max="10" required
                     class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                     placeholder="入住人数">
            </div>

            <!-- 预订信息预览 -->
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="font-medium text-gray-800 mb-3">预订详情</h3>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">房间价格:</span>
                  <span id="price_display" class="text-gray-800">¥0/晚</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">入住天数:</span>
                  <span id="days_display" class="text-gray-800">0天</span>
                </div>
                <div class="border-t border-gray-200 my-2 pt-2 flex justify-between font-medium">
                  <span class="text-gray-700">总计:</span>
                  <span id="total_display" class="text-primary">¥0</span>
                </div>
              </div>
            </div>

            <button type="submit" class="w-full bg-primary text-white py-3 px-4 rounded-md hover:bg-primary/90 transition-colors font-semibold shadow-sm hover:shadow">
              确认预订
            </button>
          </form>
        </div>

        <!-- 预订须知卡片 -->
        <div class="bg-white rounded-xl shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-3">预订须知</h3>
          <ul class="space-y-2 text-sm text-gray-600">
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>入住时间为下午14:00后，退房时间为中午12:00前</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>如需提前入住或延迟退房，请提前联系我们</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>预订后如需取消，请至少在入住前24小时通知</span>
            </li>
            <li class="flex items-start">
              <i class="fas fa-info-circle text-primary mt-0.5 mr-2"></i>
              <span>房间价格已包含服务费和税费</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  const checkInInput = document.getElementById('check_in');
  const checkOutInput = document.getElementById('check_out');
  const roomIdInput = document.getElementById('room_id');
  const selectedRoomDisplay = document.getElementById('selected_room_display');
  const priceDisplay = document.getElementById('price_display');
  const daysDisplay = document.getElementById('days_display');
  const totalDisplay = document.getElementById('total_display');
  const selectRoomBtns = document.querySelectorAll('.select-room-btn');
  const searchForm = document.getElementById('search-form');
  const resetFilterBtn = document.getElementById('reset-filter');
  const roomItems = document.querySelectorAll('.room-item');
  const roomCountEl = document.getElementById('room-count');
  const noResultsEl = document.getElementById('no-results');

  // 存储当前选择的房间价格
  let currentRoomPrice = 0;

  // 设置最小日期为今天
  const today = new Date().toISOString().split('T')[0];
  checkInInput.min = today;
  checkOutInput.min = today;

  // 默认设置入住日期为今天，退房日期为明天
  checkInInput.value = today;
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  checkOutInput.value = tomorrow.toISOString().split('T')[0];

  // 当入住日期改变时，更新退房日期的最小值
  checkInInput.addEventListener('change', updateMinCheckOutDate);

  // 当日期改变时，更新总价
  checkInInput.addEventListener('change', calculateTotal);
  checkOutInput.addEventListener('change', calculateTotal);

  // 房间选择按钮点击事件
  selectRoomBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      if (this.disabled) return;

      const roomId = this.getAttribute('data-room-id');
      const roomName = this.getAttribute('data-room-name');
      const roomPrice = this.getAttribute('data-room-price');

      // 更新表单值
      roomIdInput.value = roomId;
      selectedRoomDisplay.value = roomName;
      currentRoomPrice = parseFloat(roomPrice);

      // 更新显示价格
      priceDisplay.textContent = `¥${currentRoomPrice}/晚`;

      // 重新计算总价
      calculateTotal();

      // 高亮显示选中的房间
      document.querySelectorAll('.room-item').forEach(roomEl => {
        roomEl.classList.remove('ring-2', 'ring-primary', 'ring-opacity-50');
      });
      this.closest('.room-item').classList.add('ring-2', 'ring-primary', 'ring-opacity-50');
    });
  });

  // 搜索表单提交事件
  searchForm.addEventListener('submit', function(e) {
    e.preventDefault();
    filterRooms();
  });

  // 重置筛选按钮事件
  resetFilterBtn.addEventListener('click', function() {
    searchForm.reset();
    filterRooms();
  });

  // 更新退房日期最小值
  function updateMinCheckOutDate() {
    checkOutInput.min = this.value;

    // 如果退房日期早于入住日期，自动调整
    if (checkOutInput.value && checkOutInput.value < this.value) {
      checkOutInput.value = this.value;
    }
  }

  // 计算入住天数和总价
  function calculateTotal() {
    if (!checkInInput.value || !checkOutInput.value || currentRoomPrice <= 0) {
      return;
    }

    const checkIn = new Date(checkInInput.value);
    const checkOut = new Date(checkOutInput.value);

    // 计算天数差
    const timeDiff = checkOut - checkIn;
    const dayDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));

    // 确保天数不为负
    const days = Math.max(dayDiff, 1);
    const total = currentRoomPrice * days;

    // 更新显示
    daysDisplay.textContent = `${days}天`;
    totalDisplay.textContent = `¥${total.toFixed(2)}`;
  }

  // 筛选房间
  function filterRooms() {
    const keyword = document.getElementById('search-keyword').value.toLowerCase();
    const priceRange = document.getElementById('price-range').value;
    const roomType = document.getElementById('room-type').value;
    const capacity = document.getElementById('capacity').value;

    let visibleCount = 0;

    roomItems.forEach(item => {
      const name = item.getAttribute('data-name');
      const price = parseFloat(item.getAttribute('data-price'));
      const type = item.getAttribute('data-type');
      const cap = parseInt(item.getAttribute('data-capacity'));

      // 关键词筛选
      const keywordMatch = keyword === '' || name.includes(keyword);

      // 价格范围筛选
      let priceMatch = true;
      if (priceRange !== 'all') {
        if (priceRange === '0-200') priceMatch = price >= 0 && price < 200;
        else if (priceRange === '200-500') priceMatch = price >= 200 && price < 500;
        else if (priceRange === '500-1000') priceMatch = price >= 500 && price < 1000;
        else if (priceRange === '1000+') priceMatch = price >= 1000;
      }

      // 房间类型筛选
      const typeMatch = roomType === 'all' || type === roomType;

      // 容纳人数筛选
      let capacityMatch = true;
      if (capacity !== 'all') {
        if (capacity === '1') capacityMatch = cap === 1;
        else if (capacity === '2') capacityMatch = cap === 2;
        else if (capacity === '3') capacityMatch = cap >= 3 && cap <= 4;
        else if (capacity === '5+') capacityMatch = cap >= 5;
      }

      // 所有条件都满足则显示
      const shouldShow = keywordMatch && priceMatch && typeMatch && capacityMatch;

      if (shouldShow) {
        item.style.display = '';
        visibleCount++;
      } else {
        item.style.display = 'none';
      }
    });

    // 更新房间计数
    roomCountEl.textContent = `共 ${visibleCount} 个房间`;

    // 显示/隐藏无结果提示
    if (visibleCount === 0) {
      noResultsEl.classList.remove('hidden');
    } else {
      noResultsEl.classList.add('hidden');
    }
  }

  // 初始化计算
  calculateTotal();
});
</script>
{% endblock %}
